package com.sunmi.usercenter.ui.activity.fragment;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.sunmi.usercenter.Constant;
import com.sunmi.usercenter.R;
import com.sunmi.usercenter.bean.FmInfo;
import com.sunmi.usercenter.bean.Result;
import com.sunmi.usercenter.bean.VerificationcodeBean;
import com.sunmi.usercenter.bean.rpc.ReqCheckUserName;
import com.sunmi.usercenter.bean.rpc.ReqGetVerificationCode;
import com.sunmi.usercenter.ui.component.LoadingDialog;
import com.sunmi.usercenter.utils.Validator;

import org.apache.http.Header;

import java.lang.reflect.Type;

/**
 * 项目名称：Sunmi-User-Center
 * 类描述：找回密码的界面
 * 创建人：Abtswiath丶lxy
 * 创建时间：2016/6/7 11:39
 * 修改人：longx
 * 修改时间：2016/6/7 11:39
 * 修改备注：
 */
public class RetrievePsdFragment extends SuperFragment implements OnClickListener ,TextWatcher{

    private View mView;
    private TextView mTxtTitle, mTxtError, mBtnNext;
    private EditText mTxtUsername;
    private RelativeLayout mRelBack,mRelClear;
    private LoadingDialog mLoadingDialog;
    private String registerMode;
    private String language;
    private boolean isEN;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    /**
     * 初始化
     */
    private void initView() {
        mActivity.SetStatusColorf5f5f5();


        mTxtTitle = (TextView) mView.findViewById(R.id.title);
        layoutTitle(mTxtTitle);
        mTxtUsername = (EditText) mView.findViewById(R.id.txt_username);
        mTxtError = (TextView) mView.findViewById(R.id.txt_error);
        mBtnNext = (TextView) mView.findViewById(R.id.btn_next);
        mRelBack = (RelativeLayout) mView.findViewById(R.id.back);
        mRelClear = (RelativeLayout) mView.findViewById(R.id.rel_clear);
        mRelClear.setVisibility(View.GONE);
        mRelClear.setOnClickListener(this);
        mTxtError.setVisibility(View.INVISIBLE);
        mBtnNext.setOnClickListener(this);
        mRelBack.setOnClickListener(this);
        mTxtUsername.addTextChangedListener(this);
        language = getResources().getConfiguration().locale.getCountry();  // 得到当前系统的语言
        if (!language.equals("CN")) {
            isEN = true;
            mTxtUsername.setHint(getString(R.string.please_input_email));
        } else {
            isEN = false;
            mTxtUsername.setHint(getString(R.string.please_input_phone_or_email));
        }
    }

    /**
     * 点击下一步
     */
    private void clickNext() {
        final String username = mTxtUsername.getText().toString();
        if (isEN) {
            if (Validator.isEmail(username)) {
                registerMode = RegisterFragment.EMAIL;
                mLoadingDialog = LoadingDialog.createDialog(getActivity(), getString(R.string.verification_mail_ing));
                checkUsername(username);
            } else {
                showToast(getString(R.string.mail_input_error));
                return;
            }
        } else {
            if (Validator.isMobile(username) || Validator.isEmail(username)) {
                if (Validator.isMobile(username)) {
                    registerMode = RegisterFragment.PHONE;
                    mLoadingDialog = LoadingDialog.createDialog(getActivity(), getString(R.string.verification_phone_ing));
                } else {
                    registerMode = RegisterFragment.EMAIL;
                    mLoadingDialog = LoadingDialog.createDialog(getActivity(), getString(R.string.verification_mail_ing));
                }
                checkUsername(username);
            } else {
                showToast(getString(R.string.phone_mail_error));
                return;
            }
        }
    }

    private void checkUsername(final String username) {
        mLoadingDialog.show();
        ReqCheckUserName checkUserName = new ReqCheckUserName();
        checkUserName.setUserName(username);
        mHttpController.checkUsername(checkUserName, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
                String json = new String(arg2);
                Gson gson = new Gson();
                @SuppressWarnings("rawtypes")
                Result result = null;
                try {
                    result = gson.fromJson(json, Result.class);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (result != null) {
                    if (result.code == 1) {
                        mLoadingDialog.dismiss();
                        mTxtError.setVisibility(View.VISIBLE);
                    } else {
                        sendCode(username);
                        mTxtError.setVisibility(View.INVISIBLE);
                    }
                } else {
                    showToast(getString(R.string.req_error));
                    mLoadingDialog.dismiss();
                }
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
                showToast(getString(R.string.req_error));
                mLoadingDialog.dismiss();
            }
        });
    }


    /**
     * 发送验证码
     *
     * @param username
     */
    private void sendCode(final String username) {
        ReqGetVerificationCode reqGetVerificationCode = new ReqGetVerificationCode();
        reqGetVerificationCode.setUserName(username);
        if (!getActivity().getResources().getConfiguration().locale.getCountry().equals("CN")) {
            reqGetVerificationCode.setLanguage(1);
        }
        mHttpController.getVerificationCode4Retrieve(reqGetVerificationCode, new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                String json = new String(bytes);
                Gson gson = new Gson();
                Type type = new TypeToken<Result<VerificationcodeBean>>() {
                }.getType();

                Result<VerificationcodeBean> result = null;
                try {
                    result = gson.fromJson(json, type);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (result != null) {
                    if (result.code == 1) {
//						VerificationcodeBean verificationcodeBean = result.getData();
//						InputToCode inputToCode = new InputToCode();
//						Constant.mInputToCode.setCode(verificationcodeBean.getCode());
                        Constant.mInputToCode.setSelectMode(registerMode);
                        Constant.mInputToCode.setUsername(username);
                        Constant.mInputToCode.setFramgment(2);
                        openFM(new FmInfo(InputCodeFragment.class, Constant.mInputToCode));
                    } else if (result.code == 160038) {
                        showToast(getString(R.string.code_send_failed));
                    } else if (result.code == 160042) {
                        showToast(getString(R.string.the_address_error_to_phone));
                    } else if (result.code == 160039 || result.code == 160040 || result.code == 160041) {
                        showToast(getString(R.string.phone_get_code_max_error));
                    } else {
                        showToast(getString(R.string.code_send_failed));
                    }
                } else {
                    showToast(getString(R.string.get_code_error));
                }
                mLoadingDialog.dismiss();
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
                showToast(getString(R.string.req_error));
                mLoadingDialog.dismiss();
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        return mView = inflater.inflate(R.layout.fragment_retrieve_password, container, false);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                onBack();
                break;
            case R.id.btn_next:
                clickNext();
                break;
            case R.id.rel_clear:
                mTxtUsername.setText("");
                break;
            default:
                break;
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
if(s.length()>0){
    mRelClear.setVisibility(View.VISIBLE);
}else{
    mRelClear.setVisibility(View.GONE);
}
    }
}
